package com.jagochan.module.rbac.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Collections;

@Configuration
public class JagochanCorsConfiguration     {

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        CorsConfiguration jagochanCorsConfiguration = new CorsConfiguration();
        // 1.允许任何来源
        jagochanCorsConfiguration.setAllowedOriginPatterns(Collections.singletonList("*"));
        // 2.允许任何请求头
        jagochanCorsConfiguration.addAllowedHeader(CorsConfiguration.ALL);
        // 3.允许任何方法
        jagochanCorsConfiguration.addAllowedMethod(CorsConfiguration.ALL);
        // 4.允许凭证
        jagochanCorsConfiguration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", jagochanCorsConfiguration);
        CorsFilter corsFilter = new CorsFilter(source);

        FilterRegistrationBean<CorsFilter> filterRegistrationBean = new FilterRegistrationBean<>(corsFilter);
        filterRegistrationBean.setOrder(-101); // 小于 sa-token  SaServletFilter 的 Order(-100) 即可

        return filterRegistrationBean;
    }

}
